package rabbit;

import java.net.InetAddress;

import javax.annotation.Resource;

import org.apache.taglibs.standard.tag.common.sql.DataSourceUtil;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.amqp.support.converter.SimpleMessageConverter;
import org.springframework.stereotype.Component;

import entity.FahaiMongoEntity;

import mongoMapper.FahaiMongoEntityMapper;
import com.qqjf.common.util.date.DateUtil;
import com.rabbitmq.client.Channel;

@Component
public class Receiver  implements  ChannelAwareMessageListener{
	
	  @Resource
	    private FahaiMongoEntityMapper fahaiMongoEntityRepository;
	
    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver : " + hello);
    }
    
    @Override    
   	public void onMessage(Message message ,Channel channel) throws Exception{
   		MessageConverter messageConverter = new SimpleMessageConverter();
   		try { 
   		 
   		FahaiMongoEntity fahaiMongoEntity = (FahaiMongoEntity)messageConverter.fromMessage(message);
   		System.out.println("Receiver : " + fahaiMongoEntity.getBody());
   		
   		
   					//LawsuitInquiryBean inquiryBean = (LawsuitInquiryBean)messageConverter.fromMessage(message);
   					if("xdadmin-dev1".equals(InetAddress.getLocalHost().getHostName()) || "xdadmin-test1".equals(InetAddress.getLocalHost().getHostName())) {
   						channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
   					}else {
   						//当consumer接收到4条消息后，不再会接收其它消息，只有当这些消息被消费时，才会接收新的消息。
   						channel.basicQos(2); 
   						//deliveryTag:该消息的indexmultiple：是否批量.true:将一次性ack所有小于deliveryTag的消息。
   						channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);
   						//saveLawsuitOptimizeInfoByFahai(inquiryBean,true);	
   						fahaiMongoEntity.setCourt(InetAddress.getLocalHost().getHostName());
						fahaiMongoEntity.setBgDate(System.currentTimeMillis());
			    		fahaiMongoEntity.setPlaintiff(DateUtil.DateToString(com.qqjf.common.util.date.DateUtil.getDateByTimeStamp(System.currentTimeMillis()),"yyyy-MM-dd HH:mm:ss"));
			    		fahaiMongoEntityRepository.insert(fahaiMongoEntity);
   					}
   			} catch (Exception e) {        
   				// TODO Auto-generated catch block
   				e.printStackTrace();
   			    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false);  
   			}finally {
   				

   			}

   	}
}